﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Fmis21_10.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult LogIn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LogIn(Models.UserModel user)
        {
            //if (ModelState.IsValid)
            // {
            if (IsVaLid(user.Username, user.Password))
            {
                FormsAuthentication.SetAuthCookie(user.Username, false);



                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Login data is incorrect.");
            }
            //   }
            return View(user);
        }
        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Registration(Models.UserModel user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new MainDbEntities())
                {
                    var crypto = new SimpleCrypto.PBKDF2();

                    var encrpPass = crypto.Compute(user.Password);

                    var sysUser = db.SystemUsers.Create();

                    sysUser.Username = user.Username;
                    sysUser.Password = encrpPass;
                    sysUser.PasswordSalt = crypto.Salt;
                    sysUser.Roles = user.Roles;
                    sysUser.UserId = Guid.NewGuid();

                    db.SystemUsers.Add(sysUser);
                    db.SaveChanges();

                    return RedirectToAction("Index", "Home");


                }
            }
            return View();
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public bool IsVaLid(string username, string password)
        {
            var crypto = new SimpleCrypto.PBKDF2();

            bool isvalid = false;
            using (var Db = new MainDbEntities())
            {
                var user = Db.SystemUsers.FirstOrDefault(u => u.Username == username);
                if (user != null)
                {
                    if (user.Password == crypto.Compute(password, user.PasswordSalt))
                    {
                        isvalid = true;
                        Session["Roles"] = user.Roles;
                    }
                }
            }



            return isvalid;
        }
    }
}
